package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo> implements ApartmentInfoService {

    @Autowired
    GraphInfoService graphInfoService;
    @Autowired
    ApartmentFacilityService apartmentFacilityService;
    @Autowired
    ApartmentLabelService apartmentLabelService;

    @Autowired
    ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    FacilityInfoService facilityInfoService;

    @Autowired
    LabelInfoService labelInfoService;

    @Autowired
    FeeValueService feeValueService;

    @Autowired
    ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    GraphInfoMapper graphInfoMapper;

    @Autowired
    FacilityInfoMapper facilityInfoMapper;

    @Autowired
    LabelInfoMapper labelInfoMapper;

    @Autowired
    FeeValueMapper feeValueMapper;

    @Autowired
    RoomInfoService roomInfoService;


    @Autowired
    ProvinceInfoService provinceInfoService;

    @Autowired
    CityInfoService cityInfoService;

    @Autowired
    DistrictInfoService districtInfoService;



    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {

        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());


        Long id =apartmentSubmitVo.getId();
        boolean isUpdate = id != null;
        this.saveOrUpdate(apartmentSubmitVo);
        //this指的是当前的实现类，调用saveOrUpdate方法就会修改主表apartmentInfo的数据
        //因为还没用其他的service调用saveOrUpdate方法，所以配套，标签，杂费，图片的表都没修改，
        //只有用apartmentLabelService，graphInfoService等调用了，配套，标签，杂费，图片的表都才会修改

        if(isUpdate){
            //删除图片关系数据
            LambdaQueryWrapper<GraphInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            wrapper.eq(GraphInfo::getItemId,id);
            graphInfoService.remove(wrapper);

            //删除公寓配套关系数据
            LambdaQueryWrapper<ApartmentFacility> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(ApartmentFacility::getApartmentId,id);
            apartmentFacilityService.remove(wrapper2);

            //删除公寓标签关系数据
            LambdaQueryWrapper<ApartmentLabel> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(ApartmentLabel::getApartmentId,id);
            apartmentLabelService.remove(wrapper3);

            //删除公寓杂费关系数据
            LambdaQueryWrapper<ApartmentFeeValue> wrapper4 = new LambdaQueryWrapper<>();
            wrapper4.eq(ApartmentFeeValue::getApartmentId,id);
            apartmentFeeValueService.remove(wrapper4);
        }
        //保存图片关系数据
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        //把所有图片的ID取出来，做成一个集合
        if (!CollectionUtils.isEmpty(graphVoList)){
            //如果不是空的，就执行下面的代码，如果是空的提交的时候这里就先无数据
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>();
            //创建一个集合用来存储下面的每一个graphInfo对象
            for (GraphVo graphVo : graphVoList) {
                /*
                "graphVoList": [
                {"name": "",
                 "url": ""
                }
                {"name": "",
                 "url": ""
                }
               ]
               graphVoList里面可以有多个对象，每个大括号是一个对象，都有name和url
               */


                GraphInfo graphInfo = new GraphInfo();//创建一个GraphInfo对象（里面有四个属性）
                graphInfo.setItemType(ItemType.APARTMENT);//设置图片属于公寓类的图片（而不是房间，APARTMENT是公寓的意思）
                graphInfo.setItemId(id);//把当前公寓的id设置到item_id字段（设置图片属于哪一个具体的公寓）
                graphInfo.setName(graphVo.getName());//把传过的的vo对象中的名字拿出来，用set方法设置到graphInfo表格name字段
                graphInfo.setUrl(graphVo.getUrl());//把传过的的vo对象中的url地址拿出来，用set方法设置到graphInfo表格url字段
                graphInfoList.add(graphInfo);//把存储好各个属性的graphInfo对象，添加到集合中，
                                             // 重复这个过程，直到所有图片的信息都添加到集合中
            }
            graphInfoService.saveBatch(graphInfoList);//批量保存这个集合中的所有对象到数据库graph_info中
        }
        //保存寓配套关系数据
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        //获取公寓设施所有ID，把所有图片的ID取出来，做成一个集合
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            //如果集合是空，提交的时候这里就先无数据（先不设置公寓配套）
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(id)
                        .facilityId(facilityInfoId)
                        .build();
                //新建一个ApartmentFacility对象（跟表格apartment_facility对应），设置apartmentId和facilityId
                apartmentFacilityList.add(apartmentFacility);//重复这个过程，直到所有图片的信息都添加到集合中
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);//批量保存这个集合中的所有对象到数据库apartment_facility中
        }


        //保存公寓标签关系数据
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)){
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(id)
                        .labelId(labelId)
                        .build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }
        //保存公寓杂费关系数据
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)){
            List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(id)
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
        }
    }

    @Override
    public IPage<ApartmentItemVo> pageItemApartment(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageItemApartment(page,queryVo);
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        //1.查询公寓表数据
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(id);
        if (apartmentInfo == null) {
            return null;
        }
        //2.查询公寓图片列表
        List<GraphVo> graphVoList = graphInfoMapper.selectGraphByItemTypeAndItemId(ItemType.APARTMENT, id);

        //3.查询公寓标签列表
        List<LabelInfo> labelInfoList = labelInfoMapper.selectLabelInfoByApartmentId(ItemType.APARTMENT, id);

        //4.查询公寓配套列表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectFacilityInfoByApartmentId(ItemType.APARTMENT, id);

        //5.查询公寓杂费列表
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectFeeValueByApartmentId(id);

        //6.封装数据
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        //7.返回数据
        return apartmentDetailVo;
    }

    @Override
    public void removeApartmentById(Long id) {
        long count = roomInfoService.count(new LambdaQueryWrapper<RoomInfo>()
                .eq(RoomInfo::getApartmentId, id));
        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }


        //2.删除公寓图片
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>()
                .eq(GraphInfo::getItemType, ItemType.APARTMENT)
                .eq(GraphInfo::getItemId, id));

        //3.删除公寓配套
        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>()
                .eq(ApartmentFacility::getApartmentId, id));

        //4.删除公寓标签
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>()
                .eq(ApartmentLabel::getApartmentId, id));

        //5.删除公寓杂费
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>()
                .eq(ApartmentFeeValue::getApartmentId, id));

        //推荐先删除关联表数据，再删除主表数据。这样不用管数据库的物理主外键是否存在。
        super.removeById(id);

    }
}
